package com.project.controller;

import com.project.common.response.Result;
import com.project.model.Doctor;
import com.project.service.AuthService;
import com.project.service.UserService;
import com.project.model.User;
import com.project.common.exception.BusinessException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Size;
import org.springframework.validation.annotation.Validated;
import java.util.Arrays;
import com.project.service.DoctorService;
import jakarta.validation.constraints.Pattern;
import jakarta.servlet.http.HttpServletRequest;

@Tag(name = "认证管理", description = "用户认证相关接口")
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
@Validated
public class AuthController {

    private final AuthService authService;
    private final UserService userService;
    private final DoctorService doctorService;

    @Operation(summary = "用户登录", description = "用户名密码登录接口")
    @ApiResponse(responseCode = "200", description = "登录成功")
    @PostMapping("/login")
    public Result<LoginResponse> login(@RequestBody LoginRequest request) {
        String token = authService.login(request.getUsername(), request.getPassword());
        return Result.success(new LoginResponse(token));
    }

    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public Result<Void> register(@RequestBody @Valid RegisterRequest request) {
        // 检查用户名是否已存在
        if (userService.checkUsernameExists(request.getUsername())) {
            throw new BusinessException("用户名已存在");
        }

        // 验证角色
        if (!Arrays.asList("USER", "DOCTOR").contains(request.getRole())) {
            throw new BusinessException("无效的角色类型");
        }

        // 创建用户
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(request.getPassword());
        user.setNickname(request.getNickname());
        user.setPhone(request.getPhone());
        user.setGender(request.getGender() != null ? request.getGender() : 0);
        user.setRole(request.getRole());

        userService.createUser(user);

        // 如果是医生，创建医生信息
        if ("DOCTOR".equals(request.getRole())) {
            Doctor doctor = new Doctor();
            doctor.setUserId(user.getId());
            doctor.setStatus(0); // 待审核状态
            doctorService.save(doctor);
        }

        return Result.success(null);
    }

    @Operation(summary = "退出登录")
    @PostMapping("/logout")
    public Result<Void> logout(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            authService.logout(token);
        }
        return Result.success(null);
    }

    @Data
    @Schema(description = "登录请求参数")
    public static class LoginRequest {
        @Schema(description = "用户名", required = true, example = "admin")
        private String username;

        @Schema(description = "密码", required = true, example = "123456")
        private String password;
    }

    @Data
    @Schema(description = "登录响应结果")
    public static class LoginResponse {
        @Schema(description = "JWT Token")
        private String token;

        public LoginResponse(String token) {
            this.token = token;
        }
    }

    @Data
    @Schema(description = "注册请求参数")
    public static class RegisterRequest {
        @Schema(description = "用户名", required = true)
        @NotBlank(message = "用户名不能为空")
        @Size(min = 3, max = 20, message = "用户名长度必须在3-20个字符之间")
        private String username;

        @Schema(description = "密码", required = true)
        @NotBlank(message = "密码不能为空")
        @Size(min = 6, max = 20, message = "密码长度必须在6-20个字符之间")
        private String password;

        @Schema(description = "昵称", required = true)
        @NotBlank(message = "昵称不能为空")
        @Size(min = 2, max = 20, message = "昵称长度必须在2-20个字符之间")
        private String nickname;

        @Schema(description = "手机号（选填）")
        private String phone;

        @Schema(description = "性别：0-保密 1-男 2-女")
        private Integer gender;

        @Schema(description = "角色", required = true, allowableValues = {"USER", "DOCTOR"})
        @NotBlank(message = "角色不能为空")
        private String role;
    }
}
